import { marked } from 'marked';
import hljs from 'highlight.js';
import 'highlight.js/styles/github-dark.css';

export class ChatView {
    constructor(container) {
        this.container = container;
        this.container.className = 'flex flex-col h-full bg-white';

        // 配置 Markdown 渲染器
        marked.setOptions({
            highlight: (code, lang) => {
                if (lang && hljs.getLanguage(lang)) {
                    return hljs.highlight(code, { language: lang }).value;
                }
                return hljs.highlightAuto(code).value;
            },
            breaks: true
        });

        // 创建聊天区域
        this.chatArea = document.createElement('div');
        this.chatArea.className = 'flex-1 overflow-hidden relative';

        // 创建消息列表背景
        const messageBackground = document.createElement('div');
        messageBackground.className = 'absolute inset-0 bg-gray-50';

        // 创建消息列表容器
        this.messageList = document.createElement('div');
        this.messageList.className = 'absolute inset-0 overflow-y-auto';

        // 创建消息内容容器
        this.messageContainer = document.createElement('div');
        this.messageContainer.className = 'flex flex-col space-y-6 py-6 px-4 md:px-6 lg:px-8';

        // 组装聊天区域
        this.messageList.appendChild(this.messageContainer);
        this.chatArea.appendChild(messageBackground);
        this.chatArea.appendChild(this.messageList);

        // 创建输入区域容器
        this.inputArea = document.createElement('div');
        this.inputArea.className = 'flex-shrink-0 border-t border-gray-200 bg-white px-4 py-4 md:px-6 md:py-4 lg:px-8 lg:py-4';

        // 创建输入表单
        this.inputForm = this.createInputForm();
        this.inputArea.appendChild(this.inputForm);

        // 存储消息元素的引用
        this.messages = new Map();

        // 添加到容器
        this.container.appendChild(this.chatArea);
        this.container.appendChild(this.inputArea);

        // 添加提示文本
        this.addWelcomeMessage();
    }

    addWelcomeMessage() {
        const welcomeContainer = document.createElement('div');
        welcomeContainer.className = 'flex flex-col items-center justify-center text-center text-gray-500 my-12';
        welcomeContainer.innerHTML = `
            <div class="w-20 h-20 mb-6 text-gray-300">
                <svg fill="currentColor" viewBox="0 0 24 24">
                    <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-4h2v2h-2v-2zm1.61-9.96c-2.06-.3-3.88.97-4.43 2.79-.18.58.26 1.17.87 1.17h.2c.41 0 .74-.29.88-.67.32-.89 1.27-1.5 2.3-1.28.95.2 1.65 1.13 1.57 2.1-.1 1.34-1.62 1.63-2.45 2.88 0 .01-.01.01-.01.02-.01.02-.02.03-.03.05-.09.15-.18.32-.25.5-.01.03-.03.05-.04.08-.01.02-.01.04-.02.07-.12.34-.2.75-.2 1.25h2c0-.42.11-.77.28-1.07.02-.03.03-.06.05-.09.08-.14.18-.27.28-.39.01-.01.02-.03.03-.04.1-.12.21-.23.33-.34.96-.91 2.26-1.65 1.99-3.56-.24-1.74-1.61-3.21-3.35-3.47z"/>
                </svg>
            </div>
            <h3 class="text-2xl font-semibold mb-4 text-gray-700">有什么可以帮你的吗？</h3>
            <p class="text-base max-w-lg">我是一个AI助手，可以帮助你回答问题、编写代码、解决问题等。试着问我一些问题吧！</p>
        `;
        this.messageContainer.appendChild(welcomeContainer);
    }

    createInputForm() {
        const form = document.createElement('form');
        form.className = 'flex flex-col gap-4 bg-white rounded-2xl shadow-lg border border-gray-200 max-w-4xl  w-full min-w-[700px]';

        // 创建文本输入区域
        const textareaContainer = document.createElement('div');
        textareaContainer.className = 'relative flex-grow min-h-[20px] p-4';

        const textarea = document.createElement('textarea');
        textarea.className = 'w-full resize-none max-h-[200px] outline-none border-0 bg-transparent p-0 pr-10 focus:ring-0 focus-visible:ring-0 dark:bg-transparent text-base';
        textarea.placeholder = '输入消息...';
        textarea.rows = 1;

        // 自动调整文本框高度
        textarea.addEventListener('input', () => {
            textarea.style.height = 'auto';
            textarea.style.height = Math.min(textarea.scrollHeight, 200) + 'px';
        });

        // 处理按键事件
        textarea.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                form.dispatchEvent(new Event('submit'));
            }
        });

        // 创建底部工具栏
        const toolbar = document.createElement('div');
        toolbar.className = 'flex items-center justify-between px-4 py-3 border-t border-gray-100';

        const hint = document.createElement('div');
        hint.className = 'text-xs text-gray-500 flex items-center gap-1';
        hint.innerHTML = `
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
            </svg>
            <span>Shift + Enter 换行</span>
        `;

        const button = document.createElement('button');
        button.className = 'inline-flex items-center justify-center gap-2 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed';
        button.type = 'submit';
        button.innerHTML = `
            <span>发送</span>
            <svg class="w-4 h-4" viewBox="0 0 20 20" fill="currentColor">
                <path d="M10.894 2.553a1 1 0 00-1.788 0l-7 14a1 1 0 001.169 1.409l5-1.429A1 1 0 009 15.571V11a1 1 0 112 0v4.571a1 1 0 00.725.962l5 1.428a1 1 0 001.17-1.408l-7-14z"></path>
            </svg>
        `;

        toolbar.appendChild(hint);
        toolbar.appendChild(button);
        textareaContainer.appendChild(textarea);
        form.appendChild(textareaContainer);
        form.appendChild(toolbar);

        return form;
    }

    renderMessage(message, isStreaming = false) {
        let messageElement = this.messages.get(message);

        if (!messageElement) {
            messageElement = document.createElement('div');
            messageElement.className = `flex ${message.sender === 'user' ? 'justify-end' : 'justify-start'} animate-fade-in max-w-4xl mx-auto w-full`;

            const bubbleWrapper = document.createElement('div');
            bubbleWrapper.className = 'max-w-[85%] flex items-start gap-3 ' +
                (message.sender === 'user' ? 'flex-row-reverse' : 'flex-row');

            // 头像
            const avatar = document.createElement('div');
            avatar.className = 'w-8 h-8 rounded-full flex-shrink-0 flex items-center justify-center text-white text-sm ' +
                (message.sender === 'user' ? 'bg-blue-500' : 'bg-gray-600');
            avatar.textContent = message.sender === 'user' ? '我' : 'AI';

            // 消息气泡
            const bubble = document.createElement('div');
            bubble.className = `py-3 px-4 rounded-2xl ${
                message.sender === 'user'
                    ? 'bg-blue-500 text-white'
                    : 'bg-white text-gray-800 shadow-sm'
            }`;

            // 创建内容容器
            const contentDiv = document.createElement('div');
            contentDiv.className = 'markdown-body prose dark:prose-invert max-w-none';
            bubble.appendChild(contentDiv);

            bubbleWrapper.appendChild(avatar);
            bubbleWrapper.appendChild(bubble);
            messageElement.appendChild(bubbleWrapper);

            this.messageContainer.appendChild(messageElement);
            this.messages.set(message, messageElement);

            // 添加淡入动画
            messageElement.style.opacity = '0';
            requestAnimationFrame(() => {
                messageElement.style.transition = 'opacity 0.3s ease-in-out';
                messageElement.style.opacity = '1';
            });
        }

        // 更新消息内容
        const contentDiv = messageElement.querySelector('.markdown-body');
        if (message.sender === 'user') {
            contentDiv.textContent = message.content;
        } else {
            contentDiv.innerHTML = marked(message.content);
            // 为代码块添加复制按钮
            contentDiv.querySelectorAll('pre code').forEach(block => {
                if (!block.parentNode.querySelector('button')) {
                    const wrapper = document.createElement('div');
                    wrapper.className = 'relative group';
                    const copyButton = document.createElement('button');
                    copyButton.className = 'absolute top-2 right-2 p-1.5 rounded bg-gray-700 text-white opacity-0 group-hover:opacity-100 transition-opacity text-xs';
                    copyButton.innerHTML = `
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3"></path>
                        </svg>
                    `;
                    copyButton.onclick = () => {
                        navigator.clipboard.writeText(block.textContent);
                        copyButton.innerHTML = `
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                            </svg>
                        `;
                        setTimeout(() => {
                            copyButton.innerHTML = `
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3"></path>
                                </svg>
                            `;
                        }, 2000);
                    };
                    block.parentNode.insertBefore(wrapper, block);
                    wrapper.appendChild(block);
                    wrapper.appendChild(copyButton);
                }
            });
        }

        if (!isStreaming) {
            this.scrollToBottom();
        }
    }

    removeMessage(message) {
        const element = this.messages.get(message);
        if (element) {
            element.style.opacity = '0';
            setTimeout(() => {
                element.remove();
                this.messages.delete(message);
            }, 300);
        }
    }

    scrollToBottom() {
        this.messageList.scrollTop = this.messageList.scrollHeight;
    }

    onSendMessage(callback) {
        this.inputForm.addEventListener('submit', (e) => {
            e.preventDefault();
            const textarea = this.inputForm.querySelector('textarea');
            const message = textarea.value.trim();
            if (message) {
                callback(message);
                textarea.value = '';
                textarea.style.height = 'auto';
                textarea.focus();
            }
        });
    }

    setLoading(loading) {
        const button = this.inputForm.querySelector('button');
        const textarea = this.inputForm.querySelector('textarea');
        button.disabled = loading;
        textarea.disabled = loading;
        button.innerHTML = loading ? `
            <span>发送中</span>
            <svg class="w-4 h-4 animate-spin" viewBox="0 0 24 24" fill="none">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
        ` : `
            <span>发送</span>
            <svg class="w-4 h-4" viewBox="0 0 20 20" fill="currentColor">
                <path d="M10.894 2.553a1 1 0 00-1.788 0l-7 14a1 1 0 001.169 1.409l5-1.429A1 1 0 009 15.571V11a1 1 0 112 0v4.571a1 1 0 00.725.962l5 1.428a1 1 0 001.17-1.408l-7-14z"></path>
            </svg>
        `;
    }
}